<template>
  <div class="comWidth">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="详情描述">
        <el-input v-model="form.description" :placeholder="form.desPlace"></el-input>
        <span class="note">{{form.note}}</span>
      </el-form-item>
      <el-form-item label="是否公共">
        <el-select v-model="form.public">
        <el-option
        v-for="p in ps"
        :key="p"
        :value="p">
        </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件名称">
        <File v-for="(file,index) in files" :file="file" :files="files" :index="index" :key="index"></File>
        <AddFilename :files = "files"></AddFilename>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="medium" :disabled="isDisabled" @click="addGist">立即创建</el-button>
        <el-button size="medium" class="returnGist">
          <router-link to="/read">返回</router-link>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import http from "axios"
  import File from '@/components/File'
  import AddFilename from '@/components/AddFilename'

  export default {
    name: "Add",
    components:{File,AddFilename},
    data(){
        return{
          form:{
            desPlace:'请输入description',
            public:"true",
            description:"",
            filename:"",
            content:"",
            note:""
          },
          ps:[
            "true", "false"
          ],
          isDisabled:false,
          files:[]
        }
    },
    watch:{
        'form.description':function (newval,oldval) {
            if(newval.length ===0){
                this.form.note='详情描述不能为空';
            } else {
              this.form.note='';
            }
        }
    },
    methods:{
      addGist(){
          if(this.form.description.length ===0){
            this.form.note='详情描述不能为空';
            return;
          } else {
            this.form.note='';
          }
        var data={
          "description": this.form.description,
          "public": this.form.public
        };
        console.log(data);
        data.files={};
        var _self = this;
        for(var i=0;i<this.files.length;i++){
          var name = _self.files[i].filename;
          data.files[name] = {
            "content":_self.files[i].content
          };
        };
          http.post("https://api.github.com/gists",data,{
            headers:{
              "Authorization": "token " + localStorage.getItem("token")
            }
          })
            .then((r)=>{
              console.log(r);
              this.isDisabled = true;
              window.confirm("创建成功");
            })
            .catch();
      }
    }
  }
</script>

<style scoped>
  .comWidth{
    width:500px;
    -ms-text-align-last: left;
    text-align-last: left;
  }
  .returnGist a{
    color:#888;
  }
</style>
